/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import http from '@ohos.net.http';

import tabbarData from '../../common/indexData.js'
import logger from '../../common/Logger'
import { Util } from '../../common/Util'
import featureAbility from '@ohos.ability.featureAbility'

const TAG = 'index=====>'
export default {
    data() {
        return {
            util: new Util(),
            tabbardata: tabbarData,
            chatList: this.$app.$def.chatData,
            imgUrl: ''
        }
    },
    onInit() {
        console.info('index=====>onInit')
        //每次加载index页面，“主页”按钮的徽标消失
        this.tabbardata[0].hasDot = 0
        //绑定“操作徽标”事件
        console.info('index====>eventBus start')
        let Bus = this.$app.$def.eventBus
        let refreshIndexToast = (index) => {
            console.info('[eventBus]index====>eventBus refreshIndexToast')
            if(index === 1) {
                this.tabbardata[index].hasDot = 'dot'
            } else if(index === 0){
                this.tabbardata[0].hasDot = this.tabbardata[0].hasDot + 1
            }
        }
        this.eventReturn = Bus.$on('refreshIndexToast', refreshIndexToast)
        console.info('index====>eventBus end')
        //录音权限相关
        logger.info(`${TAG} grantPermission`)
        let context = featureAbility.getContext()
        context.requestPermissionsFromUser(['ohos.permission.MICROPHONE'], 666, function (result) {
            logger.info(`${TAG} grantPermission,requestPermissionsFromUser,result=${JSON.stringify(result)}`)
        })
        logger.info(`${TAG} enter oninit`)
        this.util.initStorage()

//        router.push({
//            uri:'pages/index/index'
//        })
    },
    onDestroy() {
        let Bus = this.$app.$def.eventBus;
        Bus.$off('refreshIndexToast',this.eventReturn)
    },
    onShow(){
        console.info("index=====>onShow()");
        this.chatList=this.$app.$def.chatData
        this.getProfileImg(this.$app.$def.uid);
        console.info('login====>getPersonalInformation')
        this.getPersonalInformation()
        this.$child('myList').onShow()
    },
    changeTabIndex(e) {
        console.info('index=====>changeTabIndex')
        //切换tab时对应的徽标消失
        if(e.index === 0){
            this.tabbardata[e.index].hasDot = 0
        } else {
            this.tabbardata[e.index].hasDot = 'none'
        }
        this.chatList=this.$app.$def.chatData
        let Bus = this.$app.$def.eventBus
        Bus.$emit('refreshMailList')
        for (let i = 0; i < this.tabbardata.length; i++) {
            let element = this.tabbardata[i];
            element.show = false;
            if (i === e.index) {
                element.show = true;
            }
        }
    },
    getProfileImg(uid){
        let httpRequest = http.createHttp();
        console.info("indexPage=====create http request to get profileImg Url");
        httpRequest.request(
            "http://" + this.$app.$def.ip + "/file/getProfileImg?uid=" + uid,
            {
                connectTimeout: 30000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            },(err, data) => {
            if (!err) {
                console.info("indexPage=====Profile Img Result : " + data.result.toString());
                let value = JSON.parse(data.result.toString());
                this.imgUrl = "http://" + value.data;
            } else {
                console.info("indexPage====> httpRequest err" + JSON.stringify(err));
                httpRequest.destroy();
            }
        }
        );
    },
    // 加载个人信息（昵称）
    getPersonalInformation(){
        let httpRequest = http.createHttp();
        console.info("indexPage=====getPersonalInformation");
        httpRequest.request(
            "http://" + this.$app.$def.ip + "/user/getPersonalInformation/" + this.$app.$def.uid,
            {
                connectTimeout: 30000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            },(err, data) => {
            if (!err) {
                console.info("indexPage=====getPersonalInformation : " + data.result.toString());
                let value = JSON.parse(data.result.toString());
                this.$app.$def.nickname = value.data.nickname;
            } else {
                console.info("indexPage====> getPersonalInformation httpRequest err" + JSON.stringify(err));
                httpRequest.destroy();
            }
            console.info("finish getPersonalInformation nickname: " + this.$app.$def.nickname);
        }
        );
    }
}

